package com.xn.app.muying.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.xn.app.muying.R;
import com.xn.app.muying.sqlite.DBManager;
import com.xn.app.muying.util.BaseActivity;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * 绑定设备
 * Created by gaoge on 2017/2/21.
 */
public class TemperatureDevicesActivity extends BaseActivity implements View.OnClickListener {

    //数据库
    private DBManager db = null;
    //标题
    private TextView title_name = null;
    //返回键
    private ImageView img_back = null;
    //当前绑定的设备号
    private TextView devices_id = null;
    //显示设备信息
    private ListView listview = null;
    //listview适配器
    private ListviewAdapter listviewAdpter = null;
    //设备信息
    private String Devices = null;
    //保存设备集合
    private ArrayList<HashMap<String, String>> list = new ArrayList<>();
    private HashMap<String, String> map = null;
    //接受页面传来的数据
    private int type = -1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //加载布局
        setContentView(R.layout.temperature_devices_activity);
        //初始化组件
        init();
    }

    //初始化
    private void init() {
        db = new DBManager(this);
        type = getIntent().getIntExtra("type", -1);
        title_name = (TextView) findViewById(R.id.title_name);
        img_back = (ImageView) findViewById(R.id.img_back);
        devices_id = (TextView) findViewById(R.id.devices_id);
        listview = (ListView) findViewById(R.id.listview);
        //设置标题
        title_name.setText("设备信息");
        img_back.setOnClickListener(this);
        //设置当前绑定的设备
        if (db.selectTemperature("Devices") != null) {
            devices_id.setText(db.selectTemperature("Devices"));
        } else {
            devices_id.setText("当前未绑定设备");
        }
        //获取设备信息
        Devices = db.selectTemperature("DevicesList");
        if (Devices != null && !Devices.equals("") && !Devices.equals("null")) {
            //排列数据
            setData();
        } else {

        }

    }

    //数据整理
    private void setData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String[] str = Devices.replace("[", "").replace("]", "").replace(" ", "").split(",");
                for (int i = 0; i < str.length; i++) {
                    map = new HashMap<String, String>();
                    String[] s = str[i].split(":");
                    map.put("devices", s[0]);
                    map.put("electricity", s[1]);
                    list.add(map);
                }
                loginHandler.sendEmptyMessage(1);
            }
        }).start();
    }

    /**
     * 单击事件
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //返回键
            case R.id.img_back:
                if (type == 0) {
                    Intent intent = new Intent(TemperatureDevicesActivity.this, TemperatureMonitoringActivity.class);
                    startActivity(intent);
                }
                finish();
                break;
        }
    }

    /**
     * 获取线程返回的数据，更新UI组件
     */
    @SuppressLint("HandlerLeak")
    Handler loginHandler = new Handler() {
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case 1:
                    listviewAdpter = new ListviewAdapter(TemperatureDevicesActivity.this, list);
                    listview.setAdapter(listviewAdpter);
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 分类列表适配器
     */
    class ListviewAdapter extends BaseAdapter {
        LayoutInflater lf = null;
        ArrayList<HashMap<String, String>> getData = new ArrayList<HashMap<String, String>>();
        ViewHolder viewHolder = null;

        public ListviewAdapter(Context context,
                               ArrayList<HashMap<String, String>> getData) {
            lf = LayoutInflater.from(context);
            this.getData = getData;
        }

        @Override
        public int getCount() {
            return getData.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @SuppressLint("InflateParams")
        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                viewHolder = new ViewHolder();
                convertView = lf.inflate(R.layout.devices_items, null);
                viewHolder.devices = (TextView) convertView.findViewById(R.id.devices);
                viewHolder.electricity = (TextView) convertView.findViewById(R.id.electricity);
                viewHolder.vibration = (ToggleButton) convertView.findViewById(R.id.vibration);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            viewHolder.devices.setText(list.get(position).get("devices"));
            viewHolder.electricity.setText("剩余电量:" + list.get(position).get("electricity") + "%");
            viewHolder.vibration.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    db.updateTemperatureSetDevices("Devices", list.get(position).get("devices"));
                    notifyDataSetChanged();
                }
            });
            if (list.get(position).get("devices").equals(db.selectTemperature("Devices"))) {
                viewHolder.vibration.setChecked(true);
                devices_id.setText(list.get(position).get("devices"));
            } else {
                viewHolder.vibration.setChecked(false);
            }
            return convertView;
        }
    }

    /**
     * 包装类
     */
    private static class ViewHolder {
        private TextView devices = null;
        private TextView electricity = null;
        private ToggleButton vibration = null;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (type == 0) {
                Intent intent = new Intent(TemperatureDevicesActivity.this, TemperatureMonitoringActivity.class);
                startActivity(intent);
            }
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
